import Food from "./Food"
import Snake from "./Snake"
import ScorePanel from "./ScorePanel"

class Game {
  food: Food
  snake: Snake
  scorePanel: ScorePanel

  direction: string = ""

  gameOver: boolean = false

  timer?: number

  constructor() {
    this.food = new Food()
    this.snake = new Snake()
    this.scorePanel = new ScorePanel()
    this.init()
  }
  init() {
    document.addEventListener("keydown", this.keydownHandler.bind(this))
    this.timer = window.setInterval(this.run.bind(this), 200)
  }

  keydownHandler(event: KeyboardEvent) {
    // this.snake.direction = event.key
    this.snake.setDirection(event.key)
  }

  run() {
    if (this.gameOver) {
      window.clearInterval(this.timer)
      // alert("Game Over!")
      return
    }
    try {
      this.snake.move()
    } catch (error) {
      this.gameOver = true
      alert(error)
    }

    // 食物被吃掉
    if (this.snake.headPosition.isEqual(this.food.position)) {
      this.snake.grow()
      this.food.regenerate()
      this.scorePanel.addScore()
    }
  }
}

export default Game
